package com.zzyl.nursing.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONNull;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.function.BiConsumer;

import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.task.vo.IotMsgNotifyData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;

/**
 * 设备数据Service业务层处理
 * 
 * @author shenkunlin
 * @date 2025-08-04
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper,DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /***
     * 新增设备数据到数据库（批量新增）
     * @param data
     */
    @Override
    public void batchInsert(IotMsgNotifyData data) {
        //1、设备数据
        //1.1 根据设备ID获取设备信息 device_id
        String deviceId = data.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceId));
        if(device==null){
            return;
        }

        //1.2 将设备设备信息赋值到DeviceData中
        // DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);

        //2、上报数据
        List<DeviceData> list = new ArrayList<>();

        //2.1 遍历services
        data.getBody().getServices().forEach(s->{
            //2.2 提取services单个对象信息
            //String serviceId = s.getServiceId();
            //处理上报时间日期
            LocalDateTime eventTime =  LocalDateTimeUtil.parse(s.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            //2.3 properties中的每个属性都需要封装成DeviceData
            s.getProperties().forEach((key, value) -> {
                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                deviceData.setId(null);
                deviceData.setFunctionId(key);
                deviceData.setDataValue(value.toString());
                deviceData.setAlarmTime(alarmTime);

                list.add(deviceData);
            });
        });

        //3、批量新增
        saveBatch(list);

        //4、写入到Redis
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,deviceId, JSONUtil.toJsonStr(list));
    }

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto)
    {
        //0、分页
        IPage<DeviceData> page = new Page<>(dto.getPageNum(),dto.getPageSize());

        //分页查询
        page = deviceDataMapper.selectPage(page,Wrappers.<DeviceData>lambdaQuery()
                //1、设备名字查询
                .eq(ObjectUtil.isNotEmpty(dto.getDeviceName()),DeviceData::getDeviceName,dto.getDeviceName())
                //2、功能ID
                .eq(ObjectUtil.isNotEmpty(dto.getFunctionId()),DeviceData::getFunctionId,dto.getFunctionId())
                //3、数据上报时间{ 开始时间和结束时间  }
                .between(ObjectUtil.isAllNotEmpty(dto.getStartTime(),dto.getEndTime()),DeviceData::getAlarmTime,dto.getStartTime(),dto.getEndTime())
        );

        //转换
        TableDataInfo<DeviceData> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        return tableDataInfo;
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        deviceData.setCreateTime(DateUtils.getNowDate());
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        deviceData.setUpdateTime(DateUtils.getNowDate());
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }
}
